package gui;

import launch.SimpleTest;

import org.newdawn.slick.*;
import org.newdawn.slick.geom.*;
import org.newdawn.slick.tests.xml.Entity;

/**
 * Button Clickable
 * @author Chacalz
 * http://slick.javaunlimited.net/viewtopic.php?p=18798
 */
public class Button extends Entity
{
    private Rectangle button;
    private boolean buttonDown = false;
    private boolean buttonReleased = false;

//    private Image image = new Image("button image");
    // private Image renderImage;

    private String text;
    //private Font font = (button's font);

    private float width;
    private float height;
    private Vector2f position;

    public Button (String text, float x, float y, float width, float height)
    {
        this.text = text;
        this.width = width;
        this.height = height;
        this.position = new Vector2f(x, y);
        this.button = new Rectangle(position.x, position.y, width, height);
       // this.renderImage = this.image.getSubImage(0, 0, this.image.getWidth(), this.image.getHeight() / 3);
    }

    public void update (GameContainer gc)
    {
        buttonReleased = false;

        if (button.contains(gc.getInput().getMouseX(), gc.getInput().getMouseY()))
        {
            if (gc.getInput().isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
            {
                buttonDown = true;
                //renderImage = image.getSubImage(0, this.image.getHeight() / 3 * 2, this.image.getWidth(), this.image.getHeight() / 3);
            }
            else
            {
                if (buttonDown)
                {
                    buttonDown = false;
                    buttonReleased = true;
                }

                // renderImage = image.getSubImage(0, this.image.getHeight() / 3, this.image.getWidth(), this.image.getHeight() / 3);
            }
        }
        else
        {
            buttonDown = false;
            // renderImage = this.image.getSubImage(0, 0, this.image.getWidth(), this.image.getHeight() / 3);
        }
    }

    public void render (Graphics gr)
    {
    	//renderImage.draw(position.x, position.y, width, height);

        int margin = ((int) width - getTextWidth(text, SimpleTest.app.getDefaultFont())) / 2;
        
        // gr.setFont(font);
        gr.drawString(text, button.getMinX() + margin, button.getMinY() + 5);
        gr.draw(button);
        
    }

    public boolean isClicked()
    {
        if (buttonReleased)
        {
            buttonReleased = false;
            return true;
        }
        return false;
    }

    private int getTextWidth (String text, Font font)
    {
        int width = 0;

        for (char ch : text.toCharArray())
            if (ch == ' ')
                width += 2;
            else
                width += font.getWidth(String.valueOf(ch));

        return width;
    }
} 
